package com.ly.hotel.view.liuwei;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ly.hotel.R;
import com.ly.hotel.common.Constants;
import com.ly.hotel.common.HandNoBinder;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.MyLogsManager;
import com.ly.hotel.common.SysConf;
import com.ly.hotel.msgevent.ControlVodEvent;
import com.ly.hotel.msgevent.SendLogEvent;
import com.ly.hotel.adaptor.HardwareInterface;

import de.greenrobot.event.EventBus;

public class GuaJiActivity extends AlertDialog {
//	private static final String[] TV_SETTING = { "最大音量", "服务灯", "开机信号源", "TV无信号待机", "留位设置", "信号输出源", };
	private String id = "";
	public void setId(String id) {
		this.id = id;
	}

	private TextView txtTip;
	private MyApplication app;
	private int minute = 0;
	private int seconds = 0;
	private Timer updateTime = new Timer(true);
	private Timer t = new Timer(true);
	private EditText noTxt;// 刷卡那个框
	private ThisHandler handlerMsg = new ThisHandler(this);
	private Context context;
	LinearLayout keyBoardContainer;
	private int length = 3;
	private String digitnum = "";
	private Button digitkeypad_1;  
    private Button digitkeypad_2;  
    private Button digitkeypad_3;  
    private Button digitkeypad_4;  
    private Button digitkeypad_5;  
    private Button digitkeypad_6;  
    private Button digitkeypad_7;  
    private Button digitkeypad_8;  
    private Button digitkeypad_9;  
    private Button digitkeypad_0;  
    private Button digitkeypad_c;  
    private Button digitkeypad_ok; 
    private TextView tipsTxt;
    private TextView tipsTxtTime;
    
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_guaji);
		app = (MyApplication) this.context.getApplicationContext();
		Log.i("hand", "退出的手牌ID是:" + id);
		txtTip = findViewById(R.id.tip);
		tipsTxtTime = findViewById(R.id.tip_time);
		keyBoardContainer = findViewById(R.id.liuwei_key_board);
		
		noTxt = findViewById(R.id.EditTextEmission);
		noTxt.setCursorVisible(false);//隐藏光标
		noTxt.setFocusable(false);//失去焦点
		noTxt.setFocusableInTouchMode(false);//虚拟键盘隐藏 
		
		initTip();
		
		setOnShowListener(new OnShowListener() {
			   
			@Override
			public void onShow(DialogInterface arg0) {
				// TODO Auto-generated method stub
				HardwareInterface.setMuteFlag(true);
			}    
		}); 
		EventBus.getDefault().post(new ControlVodEvent(ControlVodEvent.VOD_STOP));
		EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_LIUWEI_IN));
		
		if(SysConf.extendConfGetValue(SysConf.SYS_CONF_SHOUPAI_ENABLE, "0").equals("1")){
			keyBoardContainer.setVisibility(View.GONE);
		} else{
			tipsTxt = (TextView)findViewById(R.id.tipsTxt);
			tipsTxt.setText(context.getString(R.string.PasswordTips));
			noTxt.setInputType(InputType.TYPE_CLASS_NUMBER);
		} 
		
		
		//同步到外置的留位灯
		byte[] bb = {'l','l','e','d',',','o','n',(byte)0x0a,(byte)0x0d};
		try {
			if(Build.BOARD.endsWith(Constants.BOARD_TYPE_ADA801_NAME) || Build.BOARD.endsWith(Constants.BOARD_TYPE_S905_WY_NAME)){
				if(HandNoBinder.sp2 != null){
					HandNoBinder.sp2.getSerialPort().getOutputStream().write(bb);
					HandNoBinder.sp2.getSerialPort().getOutputStream().flush();
				}
			} else if(Build.BOARD.endsWith(Constants.BOARD_TYPE_ADA628_NAME)){
				if(HandNoBinder.sp != null){
					HandNoBinder.sp.getSerialPort().getOutputStream().write(bb);
					HandNoBinder.sp.getSerialPort().getOutputStream().flush();
				}
			}  else if(Build.BOARD.endsWith(Constants.BOARD_TYPE_6A648_NAME) || Build.BOARD.equals(Constants.BOARD_TYPE_ADA648_NAME)){
				if(HandNoBinder.sp2 != null){
					HandNoBinder.sp2.getSerialPort().getOutputStream().write(bb);
					HandNoBinder.sp2.getSerialPort().getOutputStream().flush();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		setup();
	}

	public GuaJiActivity(Context context, int theme) {
	    super(context, theme);
	    this.context = context;
	}
	

    public void setup() {  
        // 初始化 对象  
        digitkeypad_1 = (Button) findViewById(R.id.digitkeypad_1);  
        digitkeypad_2 = (Button) findViewById(R.id.digitkeypad_2);  
        digitkeypad_3 = (Button) findViewById(R.id.digitkeypad_3);  
        digitkeypad_4 = (Button) findViewById(R.id.digitkeypad_4);  
        digitkeypad_5 = (Button) findViewById(R.id.digitkeypad_5);  
        digitkeypad_6 = (Button) findViewById(R.id.digitkeypad_6);  
        digitkeypad_7 = (Button) findViewById(R.id.digitkeypad_7);  
        digitkeypad_8 = (Button) findViewById(R.id.digitkeypad_8);  
        digitkeypad_9 = (Button) findViewById(R.id.digitkeypad_9);  
        digitkeypad_0 = (Button) findViewById(R.id.digitkeypad_0);  
        digitkeypad_c = (Button) findViewById(R.id.digitkeypad_c);  
        digitkeypad_ok = (Button) findViewById(R.id.digitkeypad_ok);  
   
        // 添加点击事件  
        DigitPasswordKeypadOnClickListener dkol = new DigitPasswordKeypadOnClickListener();  
        digitkeypad_1.setOnClickListener(dkol);
        digitkeypad_2.setOnClickListener(dkol);  
        digitkeypad_3.setOnClickListener(dkol);  
        digitkeypad_4.setOnClickListener(dkol);  
        digitkeypad_5.setOnClickListener(dkol);  
        digitkeypad_6.setOnClickListener(dkol);  
        digitkeypad_7.setOnClickListener(dkol);  
        digitkeypad_8.setOnClickListener(dkol);  
        digitkeypad_9.setOnClickListener(dkol);  
        digitkeypad_0.setOnClickListener(dkol);  
        digitkeypad_c.setOnClickListener(dkol);  
        digitkeypad_ok.setOnClickListener(new DigitPasswordKeypadFinshOnClikcListener());  
   
        digitkeypad_1.requestFocus();
    }  
   
    private class DigitPasswordKeypadFinshOnClikcListener implements View.OnClickListener {  

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			if(noTxt.getText().toString().equals(id)){
				MyApplication.setBandNo(noTxt.getText().toString());
				Message message = new Message();
				message.what = 1;
				handlerMsg.sendMessage(message);
			}else{ 
				Log.i("liuwei", "密码错误:" + noTxt.getText().toString());
				noTxt.setText("");
				digitnum = "";
			}
		}  
    }  

    private class DigitPasswordKeypadOnClickListener implements View.OnClickListener {  

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			int viewId = v.getId();  
//			String digitnum = txtArtNo.getText().toString();
            switch (viewId) {  
            case R.id.digitkeypad_1:  
                if (digitnum.length() == length) {  
                    return;  
                } else {  
                    digitnum += 1;  
                }  
                break;  
            case R.id.digitkeypad_2:  
                if (digitnum.length() == length) {  
                    return;  
                } else {  
                    digitnum += 2;  
                }  
                break;  
            case R.id.digitkeypad_3:  
                if (digitnum.length() == length) {  
                    return;  
                } else {  
                    digitnum += 3;  
                }  
                break;  
            case R.id.digitkeypad_4:  
                if (digitnum.length() == length) {  
                    return;  
                } else {  
                    digitnum += 4;  
                }  
                break;  
            case R.id.digitkeypad_5:  
                if (digitnum.length() == length) {  
                    return;  
                } else {  
                    digitnum += 5;  
                }  
                break;  
            case R.id.digitkeypad_6:  
                if (digitnum.length() == length) {  
                    return;  
                } else {  
                    digitnum += 6;  
                }  
                break;  
            case R.id.digitkeypad_7:  
                if (digitnum.length() == length) {  
                    return;  
                } else {  
                    digitnum += 7;  
                }  
                break;  
            case R.id.digitkeypad_8:  
                if (digitnum.length() == length) {  
                    return;  
                } else {  
                    digitnum += 8;  
                }  
                break;  
            case R.id.digitkeypad_9:  
                if (digitnum.length() == length) {  
                    return;  
                } else {  
                    digitnum += 9;  
                }  
                break;  
            case R.id.digitkeypad_0:  
                if (digitnum.length() == length) {  
                    return;  
                } else {  
                    digitnum += 0;  
                }  
   
                break;  
            case R.id.digitkeypad_c:// 后退  
                if (digitnum.length() > 0) {  
                    digitnum = digitnum.substring(0, digitnum.length() - 1);  
                }  
                break;  
            }  
            // 格式化 数据  
            noTxt.setText(digitnum);  
            noTxt.setSelection(null != digitnum ? digitnum.length() : 0);  
		}  
   
    } 
    
	@Override
	protected void onStart() {
		super.onStart();
//		app.setJishiPopWindowsShow(false);
		
		new Thread() {
			public void run() {
				MyApplication.clearBandNo();
				while (!MyApplication.getBandNo().equals(id)) {
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				
//				context.sendBroadcast(new Intent(Constants.Broadcast.CALL_MENU).putExtra("flag", Constants.POINT_OPEN));
				 
				System.out.println("手牌确认完成，退出留位挂机界面");
				// noTxt.setText(MyApplication.getBandNo());
				Message message = new Message();
				message.what = 1;
				handlerMsg.sendMessage(message);

			}
		}.start();
		
		context.sendBroadcast(new Intent(Constants.Broadcast.CALL_MENU).putExtra("flag", Constants.POINT_CLOSE));
	}

	private static class ThisHandler extends Handler {
		private WeakReference<GuaJiActivity> wrActivity;

		public ThisHandler(GuaJiActivity activity) {
			wrActivity = new WeakReference<GuaJiActivity>(activity);
		}

		@Override
		public void handleMessage(Message msg) {
			GuaJiActivity act = wrActivity.get();
			switch (msg.what) {
			case 1:
				// 更新本页面文本框显示读取到的卡号
				act.noTxt.setText(MyApplication.getBandNo());
				// 打开
//				bandNoInputComplete(MyApplication.getBandNo());
				// 恢复声音
//				mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);
				HardwareInterface.setMuteFlag(false);
				if (act.updateTime != null) {
					act.updateTime.cancel();
				}

				if (act.t != null) {
					act.t.cancel();
				}
				wrActivity.get().dismiss();
				MyApplication.clearBandNo();
				HardwareInterface.setMuteFlag(false);
				act.context.sendBroadcast(new Intent(Constants.Broadcast.CALL_MENU).putExtra("flag", Constants.POINT_OPEN));
				EventBus.getDefault().post(new ControlVodEvent(ControlVodEvent.VOD_START));
				EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_LIUWEI_OUT));
				
				//同步到外置的留位灯
				byte[] bb = {'l','l','e','d',',','o','f','f',(byte)0x0a,(byte)0x0d};
				try {
					if(Build.BOARD.endsWith(Constants.BOARD_TYPE_ADA801_NAME) || Build.BOARD.endsWith(Constants.BOARD_TYPE_S905_WY_NAME)){
						if(HandNoBinder.sp2 != null){
							HandNoBinder.sp2.getSerialPort().getOutputStream().write(bb);
							HandNoBinder.sp2.getSerialPort().getOutputStream().flush();
						}
					} else if(Build.BOARD.endsWith(Constants.BOARD_TYPE_ADA628_NAME)){
						if(HandNoBinder.sp != null){
							HandNoBinder.sp.getSerialPort().getOutputStream().write(bb);
							HandNoBinder.sp.getSerialPort().getOutputStream().flush();
						}
					} else if(Build.BOARD.endsWith(Constants.BOARD_TYPE_6A648_NAME) || Build.BOARD.equals(Constants.BOARD_TYPE_ADA648_NAME)){
						if(HandNoBinder.sp2 != null){
							HandNoBinder.sp2.getSerialPort().getOutputStream().write(bb);
							HandNoBinder.sp2.getSerialPort().getOutputStream().flush();
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
				break;
			case 2:
				// TODO Auto-generated method stub 
				act.seconds--;
				act.txtTip.setText(act.minute + act.context.getString(R.string.guaji_standby_tips));
				act.tipsTxtTime.setText(act.seconds2Str(act.seconds));
				break;
			}
		}
	}

	private void initTip() {

		//服务器设置的
		minute = app.getLiuweiTime();
		
		if (minute == 0) {
			return;
		}
		seconds = minute * 60;
		txtTip.setText(minute + "分钟后自动进入待机状态");
		tipsTxtTime.setText(seconds2Str(seconds));
		updateTime.schedule(new TimerTask() {

			@Override
			public void run() {

				Message message = new Message();
				message.what = 2;
				handlerMsg.sendMessage(message);
			}

		}, 0, 1000);
		t.schedule(new TimerTask() {

			@Override
			public void run() {
				Log.i("GusJiActivity", "倒数完毕，解锁");
				dismiss();
			}
		}, seconds * 1000);
	}

	private String seconds2Str(int seconds) {
		int minute = seconds / 60;
		int second = seconds % 60;
		String tmp1;
		String tmp2;
		
		if(minute<=9){
			tmp1 = "0" + minute;
		}else{
			tmp1 = "" + minute;
		}
		
		if(second<=9){
			tmp2 = "0" + second;
		}else{
			tmp2 = "" + second;
		}
		return tmp1 + ":" + tmp2;
	}

	@Override
	public void onBackPressed() {
	}
}
